package com.linkwechat.web.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linkwechat.common.core.domain.entity.SysDept;
import com.linkwechat.common.core.domain.model.LoginUser;
import com.linkwechat.common.enums.DelFlagEnum;
import com.linkwechat.common.utils.*;
import com.linkwechat.common.vo.CommonRsp;
import com.linkwechat.domain.WeCorpAccount;
import com.linkwechat.domain.wecom.entity.department.WeDeptEntity;
import com.linkwechat.domain.wecom.query.department.WeDeptQuery;
import com.linkwechat.domain.wecom.vo.department.QwDeptListVO;
import com.linkwechat.domain.wecom.vo.department.WeDeptVo;
import com.linkwechat.domain.wecom.vo.user.QwDeptUserVO;
import com.linkwechat.fegin.WxApiFeignClient;
import com.linkwechat.mapper.WeCorpAccountMapper;
import com.linkwechat.service.IWeCorpAccountService;
import com.linkwechat.web.mapper.SysDeptMapper;
import com.linkwechat.web.service.SysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @Author 王君平
 * @Date 2024/6/11 9:48
 * @Description
 */
@Slf4j
@Service
public class NewSysDeptServiceImpl implements SysDeptService {

    @Autowired
    private WeCorpAccountMapper weCorpAccountMapper;

    @Autowired
    private IWeCorpAccountService iWeCorpAccountService;

    @Autowired
    private WxApiFeignClient wxApiFeignClient;

    @Resource
    private SysDeptMapper deptMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysDept> syncWeDepartment(String corpId) {
        ParamCheckUtil.stringEmpty( corpId,"corpId不能为空");
        WeCorpAccount weCorpAccount = iWeCorpAccountService.getCorpAccountByCorpId(corpId);
        ParamCheckUtil.objectNull(weCorpAccount,"WeCorpAccount不能为空");
        String corpSecret = weCorpAccount.getAgentSecret();//todo wjp
        CommonRsp<String> accessTokenRes = wxApiFeignClient.accessToken(weCorpAccount.getCorpId(),corpSecret);
        String accessToken = FeignUtil.extractResult(accessTokenRes);
        ParamCheckUtil.stringEmpty(accessToken,"accessTokenRes不能为空");

        CommonRsp<QwDeptListVO> deptcommonRsp = wxApiFeignClient.deptList(accessToken,null);
        QwDeptListVO deptRes = FeignUtil.extractResult(deptcommonRsp);
        if(deptRes == null){
            return new ArrayList<>();
        }
        List<QwDeptListVO.department_id> department_idList = deptRes.getDepartment_id();
        if(CollectionUtils.isEmpty(department_idList)){
            return new ArrayList<>();
        }

        List<SysDept> sysDeptList = department_idList.stream().map(dept -> {
            SysDept d = new SysDept();
            d.setDeptId(dept.getId());
            d.setParentId(dept.getParentid());
            //设置ancestors
            TreeSet<Long> parentIds = new TreeSet<>();
            getParentDeptIds(department_idList,dept.getId(),parentIds);
            d.setAncestors(parentIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
            //d.setDeptName(dept.getName());
            //d.setDeptEnName(dept.getNameEn());
            //d.setLeader(String.join(",", dept.getDepartmentLeader()));
            d.setOrderNum(dept.getOrder());
            return d;
        }).collect(Collectors.toList());
        deptMapper.delete(new LambdaQueryWrapper<SysDept>());//删除全部
        for (int i = 0; i < sysDeptList.size(); i++) {
            SysDept sysDept = sysDeptList.get(i);
            deptMapper.insert(sysDept);
        }
        return sysDeptList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<QwDeptUserVO.dept_user> syncWeUser(String corpId) {
        ParamCheckUtil.stringEmpty( corpId,"corpId不能为空");
        WeCorpAccount weCorpAccount = iWeCorpAccountService.getCorpAccountByCorpId(corpId);
        ParamCheckUtil.objectNull(weCorpAccount,"WeCorpAccount不能为空");
        String contactSecret = weCorpAccount.getContactSecret();
        ParamCheckUtil.stringEmpty(contactSecret,"contactSecret不能为空");
        CommonRsp<String> accessTokenRes = wxApiFeignClient.contactAccessToken(weCorpAccount.getCorpId(),contactSecret);
        String contactAccessToken = FeignUtil.extractResult(accessTokenRes);
        ParamCheckUtil.stringEmpty(contactAccessToken,"contactaccessTokenRes不能为空");

        List<QwDeptUserVO.dept_user> list = new ArrayList<>();
        getDeptUser(list,contactAccessToken,null);
        //TODO
        log.info(JSON.toJSONString(list));
        return list;
    }

    private void getDeptUser(List<QwDeptUserVO.dept_user> list,String contactAccessToken,String next_cursor){
        CommonRsp<QwDeptUserVO> deptUsercommonRsp = wxApiFeignClient.deptUser(contactAccessToken,next_cursor);
        QwDeptUserVO vo = FeignUtil.extractResult(deptUsercommonRsp);
        if(CollectionUtil.isNotEmpty(vo.getDept_user())) {
            list.addAll(vo.getDept_user());
        }
        next_cursor = vo.getNext_cursor();
        if(StringUtil.isNotEmpty(next_cursor)){
            getDeptUser(list,contactAccessToken,next_cursor);
        }
    }

    /**
     * 递归获取父级ids
     * @param weDeptEntityList 列表
     * @param currentId 当前节点
     * @param parentIds 父节点ID列表
     */
    private static void getParentDeptIds(List<QwDeptListVO.department_id> weDeptEntityList, Long currentId, TreeSet<Long> parentIds){
        for (QwDeptListVO.department_id weDept : weDeptEntityList) {

            if(Objects.equals(0L,currentId)){
                return;
            }
            //判断是否有父节点
            if (currentId.equals(weDept.getId())) {
                parentIds.add(weDept.getParentid());
                getParentDeptIds(weDeptEntityList, weDept.getParentid(), parentIds);
            }
        }
    }


}
